var SELECT_LOGIN_ELEMENT_NAME = "gSwitcher-selectLogin"
var FORM_LOGIN_ELEMENT_NAME = "gSwitcher-formLogin";
var SIGN_OUT_EVENT = "signOut";
var ON_TAB_LOGOUT = "onTabLogout";
var ON_TAB_LOGIN = "onTabLogin";
var GET_PASSWORD_FOR = "getPasswordFor";
var waitEnable = true;
var currentAccounts;
var signOutElement;
var signOutHref;
var selectBox;

function init(){
// bind event
initUI();
bindEvent();
log("init content script");
/*
signOutElement = getDocumentElementForDropDown();
alert(signOutElement);
if(signOutElement == null) {
    log("No sign out element found");
    return;
}
*/
//sendOnTabSignIn();
selectBox = document.createElement("span");
getAccountsFromStore(true);
}

function initUI(){

}

function bindEvent(){
  $('form.account').submit(function(){
    var username = $('input[name=username]').val();
    var password = $('input[name=password]').val();
  });
}


//====================================================================
//                              UI VIEW
//====================================================================
function updateView(accounts, insert) {
        log("updating view");
        signOutHref = signOutElement.href;
        //updateSelectBox(accounts);
        if(insert) {
            log("inserting select box");
            //signOutElement.parentNode.replaceChild(selectBox, signOutElement);
            //element.firstChild.addEventListener("click", onSelectChange, true);
        }
}

function getDocumentElementForDropDown() {
	try {
		var $element = $('.top-nav-info');
		if($element) {
			//var links = element.getElementsByTagName("a");
                        var links = $element.find("a");
                        links.each(function(i){
                            alert($(this));
                        });
                        /*
			for (var i = 0; i < links.length; i++) {
				if (links[i].href) { 
					if(links[i].href.toLowerCase().indexOf("logout") > 0 && links[i].href.toLowerCase().indexOf("switcher") == -1) {
						return links[i];
					}
				}
			}
                        */
		}
		return null;
	} catch (e) {
		logError("error : " + e); return null;
	}
}

//====================================================================
//                              STORE LAYER
//account is define by an email and a password
//the storing is implemented in the background page
//====================================================================

function getAccountsFromStore() {
        log("getting the list of account from the local store");
        chrome.extension.sendRequest({action: "getAccounts"}, function(response) {
                  log("getting back the list of accounts");
                  currentAccounts = response;
                  updateView(response, true);
        });
}

function setUsernameToSignIn(usernameToSignIn) {
        log("setting username to sign in  : " + usernameToSignIn);
        chrome.extension.sendRequest({action: "setUsernameToSignIn", username : usernameToSignIn}, function(response) {
                  log("account setted!");
        });
}

function getUsernameToSignIn() {
        log("getting username to sign in");
        chrome.extension.sendRequest({action: "getUsernameToSignIn"}, function(response) {
                log("account to sign in is :" + response);
                setUsernameToSignInToForm(response);
        });
}

function getAdSenseAutoSignInValue() {
        log("getting AdSenseAutoSignIn settings");
        chrome.extension.sendRequest({action: "getAdSenseAutoSignInValue"}, function(response) {
                log("getAdSenseAutoSignInValue value :" + response.autoSingIn + " account : " + response.account + " password : " + response.password);
                if(response.autoSingIn == true) {
                        log("Auto sign in on google adsense");
                        setTimeout("loginOnAdSense('" + response.account + "','" + response.password + "')", 2500);
                } else {
                        log("Auto sign in for google adsense is off");
                }
        });
}

function loginOnAdSense(account, password) {
        var element = document.getElementById("awglogin")
        if(element) {
                var frame = element.contentDocument;
                frame.getElementById("Email").value = account;
                if(password != null) {
                        frame.getElementById("Passwd").value = password;
                        frame.forms[0].submit();
                }
        }
}

//====================================================================
//Receiving broadcast event from background page
//====================================================================

chrome.extension.onRequest.addListener(
        function(request, sender, sendResponse) {
                log("message received" + request.tabid);
                if(isGooglePage()) {
                        document.location.reload();
                }
        }
);


//======================================================================
// log abstraction
//======================================================================
//if (!window.console) console = {};
//console.log = console.log || function {}
//console.info = console.info || function {}

function log(msg) {
        console.info(msg);
}

function logError(msg) {
        console.error(msg);
}
